package com.talking.view.bodyframe;

import com.talking.controller.usermsg.GetMailCodeController;
import com.talking.controller.usermsg.UpdateUserMsgController;
import com.talking.view.componentpojo.ColorObj;
import com.talking.view.componentpojo.JScrollPaneConfig;
import com.talking.pojo.SystemVariable;
import com.talking.pojo.User;
import com.talking.view.component.*;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 个人中心面板
 *头像展示
 * 密码修改
 *
* */
public class UserMsgFrame extends JFrame{

    private LeftPanel leftPanel;       //左边面板
    private HeadImage headImage;     //头像
    private IButton uploadButton;       //上传

    private JPanel rightPanel;          //右边面板，主要存放个人资料面板与修改密码面板
    private SpringLayout rightSpring;
    private CardLayout rightCard;           //右侧面板的卡片布局
    private MessagePanel messagePanel;       //个人资料面板
    private UpdatePWDPanel updatePWDPanel;      //修改密码面板

    private JTextField idField;
    private JTextField emailField;
    private JTextField createFiled;
    private JTextField ipFiled;

    private JTextField nameField;
    private JLabel sexFiled;
    private JLabel sexFiled1;
    private JTextField yearsFiled;
    private JTextArea describeArea;
    private JScrollPane describeJScrollPane;

    private final int width= 850;
    private final int height= 550;
    private final int headImageSize = 140;
    private User user;
    private boolean isEdit = false;
    private String selectSex = "";

    FileDialog d1 = new FileDialog(this, "选择头像图片", FileDialog.LOAD);

    public UserMsgFrame(){

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setTitle("个人信息");
        leftPanel = new LeftPanel();
        rightPanel = new JPanel();
        rightCard = new CardLayout();
        messagePanel = new MessagePanel();
        updatePWDPanel = new UpdatePWDPanel();

        this.setResizable(false);
        this.setLayout(new GridLayout(1,2));
        this.setBounds((int)(screenSize.getWidth()-width)/2,150,width,height);
        this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);

        rightPanel.setLayout(rightCard);
        rightPanel.add(messagePanel,"0");
        rightPanel.add(updatePWDPanel,"1");

        this.add(leftPanel);
        this.add(rightPanel);


    }
    public void setSpring(SpringLayout springLayout,JComponent currentComponent,JComponent north,int WestPad,int NorthPad,JComponent west){
        springLayout.putConstraint(SpringLayout.NORTH,currentComponent,NorthPad,SpringLayout.NORTH,north);
        springLayout.putConstraint(SpringLayout.WEST,currentComponent,WestPad,SpringLayout.WEST,west);
    }

    public void showFrame(){
        this.dispose();
        this.user = SystemVariable.getCurrentUser();
        this.updateContent(user);

        rightCard.show(rightPanel,"0");
        this.setVisible(true);

    }
    public void updateContent(User user){
        this.user = user;
        this.headImage.setImage("/u"+user.getUser_id());
        this.idField.setText(String.valueOf(user.getUser_id()));
        this.emailField.setText(user.getUser_mail());
        this.createFiled.setText(String.valueOf(user.getCreate_time()));
        this.ipFiled.setText(String.valueOf(user.getIp()));

        this.nameField.setText(String.valueOf(user.getUser_name()));

        if (user.getUser_sex().equals("男")) {
            sexFiled.setIcon(new ImageIcon("image/bodyframe/user/m.png"));
            sexFiled1.setIcon(new ImageIcon("image/bodyframe/user/w.png"));
        }
        else {
            sexFiled.setIcon(new ImageIcon("image/bodyframe/user/w.png"));
            sexFiled1.setIcon(new ImageIcon("image/bodyframe/user/m.png"));
        }

        this.yearsFiled.setText(String.valueOf(user.getUser_age()));
        this.describeArea.setText(String.valueOf(user.getUser_describe()));
        leftPanel.repaint();
        this.setIconImage(new ImageIcon("temp/").getImage());
        this.repaint();
    }

    //左边面板
    public class LeftPanel extends JPanel{
        public LeftPanel(){
            headImage = new HeadImage(headImageSize,null,new HeadAdapter());
            uploadButton = new IButton("上传头像",ColorObj.mainThemeColor,true);


            this.setLayout(null);
            headImage.setLocation((width/2-headImageSize)/2,120);
            uploadButton.setBounds((width/2-headImageSize)/2,120+headImageSize+30,headImageSize,40);

            this.add(headImage);
            this.add(uploadButton);

            uploadButton.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (d1.getDirectory()!=null)
                        new UpdateUserMsgController(null,null,null,null,null,d1.getDirectory()+d1.getFile(),null);
                }
            });
        }
    private class HeadAdapter extends MouseAdapter{
            @Override
            public void mouseClicked(MouseEvent e){
                d1.setVisible(true);
                System.out.println("目录是："+d1.getDirectory());
                if (d1.getDirectory()!=null){
                    headImage.setTempImage(d1.getDirectory()+d1.getFile());
                }
            }
}

        public void paintComponent(Graphics g){
            super.paintComponent(g);
            GradientPaint paint = null;

            int width = this.getWidth();
            int height = this.getHeight();

            Graphics2D g2 = (Graphics2D) g;
            if (user.getUser_sex().equals("女"))
                paint =new GradientPaint(width/2, height/2,ColorObj.GENERIC2, width, height, ColorObj.GENERIC3,false);
            else
                paint =new GradientPaint(width/2, height/2,ColorObj.Matching_Gradient3, width, height, ColorObj.Matching_Gradient4,false);
            g2.setPaint(paint);

            g2.fillRect(0,0,width,height);
        }
    }


    public class MessagePanel extends JPanel{

        private TextLabel userID;
        private TextLabel userEmail;
        private TextLabel createTime;
        private TextLabel userIP;

        private EditButton editButton;
        private TextLabel userName;
        private TextLabel userSex;
        private TextLabel userYears;
        private TextLabel userDescribe;
        private JLabel updatePWD;


        private int border = 10;

        public MessagePanel(){
            rightSpring = new SpringLayout();
            userID = new TextLabel("账号：");
            idField = new JTextField();
            userEmail = new TextLabel("邮箱：");
            emailField = new JTextField();
            createTime = new TextLabel("创建时间：");
            createFiled = new JTextField();
            userIP = new TextLabel("网络地址：");
            ipFiled = new JTextField();

            editButton = new EditButton();
            userName = new TextLabel("昵称：");
            nameField = new JTextField();
            userSex = new TextLabel("性别：");
            sexFiled = new JLabel();
            sexFiled1 = new JLabel();
            userYears = new TextLabel("年龄：");
            yearsFiled = new JTextField();
            userDescribe = new TextLabel("个人说明：");
            describeArea = new JTextArea();
            describeJScrollPane = new JScrollPane(describeArea);
            updatePWD = new JLabel("修改密码");

            int fieldHeight = (int)userName.getPreferredSize().getHeight();


            //设置组件属性
            this.fieldSet(idField,emailField,createFiled,ipFiled,nameField,yearsFiled);
            this.setStyle(idField,emailField,createFiled,ipFiled,nameField,sexFiled,yearsFiled,describeArea);
            nameField.setPreferredSize(new Dimension(100,fieldHeight));
            sexFiled.setPreferredSize(new Dimension(30,fieldHeight));
            sexFiled1.setPreferredSize(new Dimension(30,fieldHeight));
            yearsFiled.setPreferredSize(new Dimension(40,fieldHeight));
            describeJScrollPane.setPreferredSize(new Dimension(1,100));
            describeArea.setBorder(null);
            describeArea.setEditable(false);
            describeArea.setBackground(ColorObj.MAIN_BACKGROUND);
            describeArea.setLineWrap(true);
            JScrollPaneConfig.setUI(describeJScrollPane);
            updatePWD.setForeground(ColorObj.buttonText);
            updatePWD.setFont(new Font("微软雅黑",Font.PLAIN,14));

            this.setLayout(rightSpring);
            this.setBackground(ColorObj.MAIN_BACKGROUND);

            setSpring(rightSpring,userID,this,30,10,this);
            setSpring(rightSpring,userEmail,userID,30,35,this);
            setSpring(rightSpring,createTime,userEmail,30,35,this);
            setSpring(rightSpring,userIP,createTime,30,35,this);

            rightSpring.putConstraint(SpringLayout.NORTH,editButton,80,SpringLayout.NORTH,userIP);
            rightSpring.putConstraint(SpringLayout.EAST,editButton,-30,SpringLayout.EAST,this);
            setSpring(rightSpring,userName,userIP,30,110,this);
            setSpring(rightSpring,userSex,userName,30,35,this);
            setSpring(rightSpring,userYears,userSex,30,35,this);
            setSpring(rightSpring,userDescribe,userYears,30,35,this);

            setSpring(rightSpring,idField,this,(int)userID.getPreferredSize().getWidth()+border,10,userID);
            setSpring(rightSpring,emailField,idField,(int)userEmail.getPreferredSize().getWidth()+border,35,userEmail);
            setSpring(rightSpring,createFiled,emailField,(int)createTime.getPreferredSize().getWidth()+border,35,createTime);
            setSpring(rightSpring,ipFiled,createFiled,(int)userIP.getPreferredSize().getWidth()+border,35,userIP);
            setSpring(rightSpring,nameField,ipFiled,(int)userName.getPreferredSize().getWidth()+border,110,userName);
            setSpring(rightSpring,sexFiled,nameField,(int)userSex.getPreferredSize().getWidth()+border,35,userSex);
            setSpring(rightSpring,yearsFiled,sexFiled,(int)userYears.getPreferredSize().getWidth()+border,35,userYears);
            setSpring(rightSpring,describeJScrollPane,userDescribe,30,35,this);
            rightSpring.putConstraint(SpringLayout.EAST,describeJScrollPane,-30,SpringLayout.EAST,this);

            setSpring(rightSpring,updatePWD,describeJScrollPane,30,10+(int)describeJScrollPane.getPreferredSize().getHeight(),this);




            this.addComponents(userID,userEmail,createTime,userIP,editButton,userName,userSex,userYears,userDescribe,updatePWD);
            this.addComponents(idField,emailField,createFiled,ipFiled,nameField,sexFiled,yearsFiled,describeJScrollPane);

            updatePWD.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    e.getComponent().setForeground(ColorObj.buttonReleasedColor);
                }
                @Override
                public void mouseReleased(MouseEvent e) {
                    e.getComponent().setForeground(ColorObj.buttonText);
                    rightCard.show(rightPanel,"1");
                }
            });

            sexFiled.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (isEdit){
                        sexFiled.setBorder(new TextBorderUtlis(ColorObj.mainThemeColor,10));
                        sexFiled1.setBorder(null);

                        String temp = ((ImageIcon)sexFiled.getIcon()).getDescription();
                        String path = temp.substring(temp.lastIndexOf("/")+1);
                        if (path.equals("m.png"))
                            selectSex = "男";
                        else
                            selectSex = "女";
                    }
                }
            });
            sexFiled1.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (isEdit){
                        sexFiled1.setBorder(new TextBorderUtlis(ColorObj.mainThemeColor,10));
                        sexFiled.setBorder(null);

                        String temp = ((ImageIcon)sexFiled1.getIcon()).getDescription();
                        String path = temp.substring(temp.lastIndexOf("/")+1);
                        if (path.equals("m.png"))
                            selectSex = "男";
                        else
                            selectSex = "女";
                    }
                }
            });
        }

        public void addComponents(JComponent... components){
            for (JComponent component : components) {
                this.add(component);
            }

        }

        public void fieldSet(JTextField... textFields){
            for (JTextField textField : textFields) {
                textField.setBorder(null);
                textField.setEditable(false);
                textField.setBackground(ColorObj.MAIN_BACKGROUND);
            }
        }

        public void setStyle(JComponent... components){
            for (JComponent component : components) {
                component.setFont(new Font("微软雅黑", Font.PLAIN,16));
                component.setForeground(new Color(85, 85, 85));
            }
        }

        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(ColorObj.buttonReleasedColor);
            g.drawLine(30,180,this.getWidth()-30,180);
        }

    }

    private class UpdatePWDPanel extends JPanel{
        private JLabel titleLabel;                   //修改密码
        private IAccountField verifyCode_Filed;     //验证码框
        private IButton getVerifyCode_JButton;   //获取验证码
        private IPasswordField passwordField;       //密码
        private IButton saveButton;   //确认按钮
        private IButton cancelButton;           //取消按钮

        private final int leftBorder = 90;
        private final int topBorder = 100;

        private final int width = 240;

        public UpdatePWDPanel(){

            titleLabel = new JLabel("修改密码");
            verifyCode_Filed = new IAccountField("验证码",leftBorder,topBorder,width/2-10,40);
            getVerifyCode_JButton = new IButton("验证码", ColorObj.mainThemeColor,true);
            passwordField = new IPasswordField("新密码",leftBorder,topBorder+50,width,40);
            saveButton = new IButton("保存",ColorObj.mainThemeColor,true);
            cancelButton = new IButton("取消",ColorObj.TEXT_TIPS,true);

            titleLabel.setBounds(20,20,140,40);
            titleLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
            getVerifyCode_JButton.setBounds(leftBorder+width/2+10,topBorder,width/2-10,40);
            saveButton.setBounds(leftBorder,topBorder+100,width,40);
            cancelButton.setBounds(leftBorder,topBorder+150,width,40);

            this.setBackground(ColorObj.MAIN_BACKGROUND);
            this.setLayout(null);

            this.add(titleLabel);
            this.add(verifyCode_Filed);
            this.add(getVerifyCode_JButton);
            this.add(passwordField);
            this.add(saveButton);
            this.add(cancelButton);

            saveButton.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    new UpdateUserMsgController(null,null,null,null,passwordField.getTheText(),null,verifyCode_Filed.getTheText());
                }
            });
            cancelButton.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    rightCard.show(rightPanel,"0");
                }
            });
            getVerifyCode_JButton.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    new GetMailCodeController();
                }
            });

        }
    }

    private class EditButton extends JLabel{
        private ImageIcon imageIcon;
        private final int width = 35;
        private final int height = 35;
        public EditButton(){
            imageIcon = new ImageIcon("image/bodyframe/user/edit.png");
            imageIcon.setImage(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_DEFAULT));
            this.setIcon(imageIcon);
            this.setPreferredSize(new Dimension(width,height));

            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    String temp = imageIcon.getDescription();
                    String path = temp.substring(temp.lastIndexOf("/")+1);
                    if (path.equals("edit1.png")){
                        setImage("image/bodyframe/user/edit.png");

                        submit(nameField,yearsFiled);
                        sexFiled.setBorder(null);
                        describeArea.setEditable(false);
                        describeJScrollPane.setBorder(null);

                        new UpdateUserMsgController(nameField.getText(),selectSex.trim().equals("")?null:selectSex,yearsFiled.getText(),describeArea.getText(),null,null,null);
                        System.out.println("名字："+nameField.getText()+"性别："+(selectSex.trim().equals("")?null:selectSex)+"年龄："+yearsFiled.getText()+"个人说明："+describeArea.getText());
                        messagePanel.remove(sexFiled1);
                        messagePanel.updateUI();
                        isEdit = false;
                    }

                    if (e.getClickCount()==2){
                        if (path.equals("edit.png")){
                            setImage("image/bodyframe/user/edit1.png");
                            selectSex = "";

                            edit(nameField,yearsFiled);
                            describeJScrollPane.setBorder(new TextBorderUtlis(ColorObj.mainThemeColor,10));

                            describeArea.setEditable(true);

                            setSpring(rightSpring,sexFiled1,nameField,(int)sexFiled.getPreferredSize().getWidth()+10,35,sexFiled);
                            messagePanel.add(sexFiled1);
                            messagePanel.updateUI();
                            isEdit = true;
                        }
                    }
                    System.out.println("这个输出是："+path);
                }
            });
        }
        private void edit(JTextComponent... components){
            for (JTextComponent component : components) {
                component.setEditable(true);
                component.setBorder(new TextBorderUtlis(ColorObj.mainThemeColor,10));
            }
        }
        private void submit(JTextComponent... components){
            for (JTextComponent component : components) {
                component.setEditable(false);
                component.setBorder(null);
            }
        }
        private void setImage(String path){
            imageIcon = new ImageIcon(path);
            imageIcon.setImage(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_DEFAULT));
            EditButton.this.setIcon(imageIcon);
        }
    }
}
